<template>
    <!-- 顶部导航栏 -->

    <view class="quiz-container flex fd-c ai-c">
        <view class="timer" v-if="!showVictoryPage">{{ formatTime(timer) }}</view>
        <!-- 答题页面 -->
        <view v-if="!showResultPage" class="quiz-content">
            <!-- 题目区域 -->

            <view class="question-number">{{ currentQuestionIndex + 1 }}{{
                currentQuestion.title }}</view>
				<view v-if="currentQuestion.is_anwser == 1"> 正确答案{{currentQuestion.correct_answer}}您选择的{{currentQuestion.answer}}</view>
            <!-- 答案选项 -->
            <view>
                <view v-for="(option, index) in currentQuestion.options" :key="index" class="option-item" :class="{
                    'selected': selectedOption === index,
                    'correct': showResult && option.isCorrect,
                    'incorrect': showResult && selectedOption === index && !option.isCorrect
                }" @click="selectOption(index)">
				
                    <view class="option-label"
                        :style="{ color: selectedOption === index || option.is_anwser == '1' ? '#fff' : 'rgba(0, 0, 0, 0.5)' }">{{
                        String.fromCharCode(65 + index) }}</view>
                    <view class="option-text">
						
                        <text style="margin-right: 28rpx;"
                            :style="{ color: selectedOption === index || option.is_anwser == '1' ? '#fff' : '#000' }">{{ option.text
                            }}</text>
                    </view>
                </view>
            </view>
        </view>
        <!-- 底部导航 -->
        <view v-if="!showResultPage" class="quiz-footer">
            <view class="navigation-buttons flex jc-c">
                <view class="nav-btn prev-btn" :class="{ 'disabled': currentQuestionIndex === 0 }"
                    @click="handlePrevious">
                    上一题
                </view>
                <view class="nav-btn next-btn" @click="handleSubmit"
                    v-if="currentQuestionIndex === questions.length - 1">
                    提交
                </view>
                <view class="nav-btn next-btn" @click="handleNext" v-else>
                    下一题
                </view>

            </view>

            <!-- 题目进度指示器 -->
            <view class="progress-dots flex ai-c">
                <view v-for="(dot, index) in questions" :key="index" class="progress-dot" :class="{
                    'current': index === currentQuestionIndex,
                    'answered': selectedAnswers[index] !== undefined
                }">
                    <text v-if="selectedAnswers[index] !== undefined" class="answer-letter">
                        {{ String.fromCharCode(65 + selectedAnswers[index]) }}
                    </text>
                </view>
            </view>
        </view>
        <!-- 结果页面 -->
        <quiz-result ref="resultRef" style="width: 100%;" v-if="showResultPage && !showVictoryPage" :time-spent="timeSpent"
            :answers="resultAnswers" :total-questions="questions.length" :ques_id="ques_id" @review="handleReview"
            @home="handleHome" @result="handleResult" />

        <!-- 胜利页面和失败页面 -->
        <quiz-victory style="width: 100%;" v-if="showVictoryPage" :points="victoryPoints"
            @view-ranking="handleViewRanking" :room_id="room_id" @play-again="handlePlayAgain" :is-victory="isVictory"
            :mingci="mingci" />
    </view>


</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import QuizResult from './quiz-result.vue'
import QuizVictory from './quiz-victory.vue'
const resultRef = ref(null)
// 定义组件属性
const props = defineProps({
    questions: {
        type: Array,
        default: () => []
    },
    timeLimit: {
        type: Number,
        default: 180 // 3分钟，单位：秒
    },
    showResult: {
        type: Boolean,
        default: false
    },
    ques_id: {
        type: String,
        default: ''
    },
    room_id: {
        type: String,
        default: ''
    }
})

// 定义组件事件
const emit = defineEmits(['back', 'submit', 'question-change', 'time-up', 'view-ranking', 'play-again'])

// 响应式数据
const currentQuestionIndex = ref(0)
const selectedOption = ref(null)
const timer = ref(props.timeLimit)
const answeredQuestions = ref([])
const timerInterval = ref(null)
const selectedAnswers = ref({}) // 记录每道题选择的答案
const showResultPage = ref(false) // 是否显示结果页面
const showVictoryPage = ref(false) // 是否显示胜利和失败页面
const timeSpent = ref(0) // 用时
const resultAnswers = ref([]) // 结果答案数组
const victoryPoints = ref(80) // 胜利获得的积分
const isVictory = ref(true) // 是否胜利
const mingci = ref(1) // 排名
// 计算当前题目
const currentQuestion = computed(() => {
    return props.questions[currentQuestionIndex.value] || {}
})
// 处理结果
const handleResult = (result) => {
    console.log('处理结果:', result)
    if(result.data.is_win == 1){
        isVictory.value = true
        victoryPoints.value = result.data.point
    } else {
        isVictory.value = false
        victoryPoints.value = 0
    }
    mingci.value = result.data.ming
    showResultPage.value = true
    showVictoryPage.value = true
}

// 格式化时间显示
const formatTime = (seconds) => {
    const minutes = Math.floor(seconds / 60)
    const remainingSeconds = seconds % 60
    return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
}

// 选择选项
const selectOption = (index) => {
    if (props.showResult) return // 如果显示结果，不允许选择

    selectedOption.value = index
    // 记录当前题目的选择答案
    selectedAnswers.value[currentQuestionIndex.value] = index

    if (!answeredQuestions.value.includes(currentQuestionIndex.value)) {
        answeredQuestions.value.push(currentQuestionIndex.value)
    }
}

// 处理返回
const handleBack = () => {
    emit('back')
}

// 处理更多选项
const handleMore = () => {
    // 可以在这里添加更多功能，如题目收藏、分享等
}

// 处理目标功能
const handleTarget = () => {
    // 可以在这里添加目标功能，如查看排行榜等
}

// 处理查看解析
const handleReview = () => {
    showResultPage.value = false
    emit('review')
}

// 处理返回首页
const handleHome = () => {
    emit('home')
}

// 处理查看排名
const handleViewRanking = () => {
    emit('view-ranking')
}

// 处理再来一场
const handlePlayAgain = () => {
    emit('play-again')
}

// 上一题
const handlePrevious = () => {
    if (currentQuestionIndex.value > 0) {
        currentQuestionIndex.value--
        // 恢复之前选择的答案
        selectedOption.value = selectedAnswers.value[currentQuestionIndex.value] || null
        emit('question-change', currentQuestionIndex.value)
    }
}

// 下一题
const handleNext = () => {
    if (currentQuestionIndex.value < props.questions.length - 1) {
        currentQuestionIndex.value++
        // 恢复之前选择的答案
        selectedOption.value = selectedAnswers.value[currentQuestionIndex.value] || null
        emit('question-change', currentQuestionIndex.value)
    }
}

// 提交
const handleSubmit = () => {
    // stopTimer()
    timeSpent.value = props.timeLimit - timer.value
    showResultPage.value = true

    // 构建结果答案数组
    resultAnswers.value = []
    let resultAnswersData = []
    for (let i = 0; i < props.questions.length; i++) {
        resultAnswers.value.push(selectedAnswers.value[i] !== undefined ? selectedAnswers.value[i] : null)
        resultAnswersData.push({
            ques_id: props.questions[i].id,
            answer: selectedAnswers.value[i] !== undefined ? selectedAnswers.value[i] : null,
        })
    }
    resultAnswersData.map(item => {
        // 0:A 1:B 2:C 3:D null
        item.answerText = item.answer === 0 ? 'A' : item.answer === 1 ? 'B' : item.answer === 2 ? 'C' : item.answer === 3 ? 'D' : null
    })
    emit('submit', {
        answeredQuestions: answeredQuestions.value,
        totalQuestions: props.questions.length,
        selectedAnswers: selectedAnswers.value,
        timeSpent: timeSpent.value,
        resultAnswersData
    })

}

// 开始计时器
const startTimer = () => {
    timerInterval.value = setInterval(() => {
        if (timer.value > 0) {
            timer.value--
        } else {
            clearInterval(timerInterval.value)
            handleSubmit()
            setTimeout(() => {
                resultRef.value.handleViewAnswers()
            }, 2000)
        }
    }, 1000)
}

// 停止计时器
const stopTimer = () => {
    if (timerInterval.value) {
        clearInterval(timerInterval.value)
        timerInterval.value = null
    }
}

// 组件挂载时启动计时器
onMounted(() => {
    startTimer()
})

// 组件卸载时清理计时器
onUnmounted(() => {
    stopTimer()
})
</script>

<style lang="scss" scoped>
.quiz-container {
    width: 100%;
    height: 100%;
}

.quiz-content {
    flex: 1;
    border-radius: 24rpx;
    width: 100%;
    padding: 32rpx;
    box-sizing: border-box;
    // height: calc(100vh - 340rpx);
    overflow-y: auto;
    background: radial-gradient(52% 52% at 72% 89%, rgba(157, 123, 243, 0.08) 0%, rgba(188, 73, 255, 0) 100%), radial-gradient(69% 69% at 4% 86%, rgba(166, 155, 253, 0.08) 0%, rgba(128, 193, 255, 0) 100%), radial-gradient(45% 74% at 94% 10%, rgba(65, 209, 200, 0.08) 0%, rgba(54, 159, 116, 0) 100%), rgba(64, 134, 238, 0.04);
}

/* 顶部导航栏 */
.quiz-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 40rpx 32rpx;
    background: #f8f9fa;
    border-bottom: 1rpx solid #e9ecef;
}

.back-button {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
}

.timer {
    width: 100%;
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
    margin-top: 64rpx;
    margin-bottom: 40rpx;
    text-align: center;
    font-family: 'semibold';
}

.header-actions {
    display: flex;
    gap: 24rpx;
}

.action-icon {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
}

.question-number {
    font-size: 30rpx;
    font-weight: 700;
    color: #000;
    margin-bottom: 40rpx;
}

.question-content {
    background: #f8f9fa;
    border-radius: 24rpx;
    padding: 32rpx;
}

.question-quote {
    font-size: 32rpx;
    color: #666;
    line-height: 1.6;
    margin-bottom: 24rpx;
    font-style: italic;
}

.question-text {
    font-size: 36rpx;
    font-weight: 600;
    color: #333;
    line-height: 1.5;
}

.option-item {
    display: flex;
    align-items: center;
    padding: 20rpx 32rpx;
    margin-bottom: 24rpx;
    background: rgba(15, 80, 220, 0.08);
    border-radius: 40rpx;
    cursor: pointer;
    transition: all 0.2s ease;
    color: #333;
}

.option-item:hover {
    border-color: #0F50DC;
}

.option-item.selected {
    background: #0F50DC;
    color: #fff;
}

.option-item.correct {
    border-color: #4caf50;
    background: #e8f5e8;
}

.option-item.incorrect {
    border-color: #f44336;
    background: #ffebee;
}

.option-label {
    border-radius: 50%;
    color: #7e7e7e;
    font-size: 24rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 24rpx;
    flex-shrink: 0;
}

.option-text {
    font-size: 28rpx;
    text-align: center;
    line-height: 1.5;
    flex: 1;
    color: #000;
}

/* 底部导航 */
.quiz-footer {
    width: 100%;
}

.navigation-buttons {
    gap: 20rpx;
    margin-bottom: 24rpx;
    margin-top: 40rpx;
}

.nav-btn {
    flex: 1;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    border-radius: 44rpx;
    font-size: 32rpx;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s ease;
}

.prev-btn {
    color: #666;
    border: 1px solid rgba(0, 0, 0, 0.3);
}

.prev-btn:not(.disabled):hover {
    background: #dee2e6;
}

.prev-btn.disabled {
    opacity: 0.5;
    cursor: not-allowed;
}

.next-btn {
    background: #0F50DC;
    color: #fff;
}

.next-btn:hover {
    background: #0d47a1;
}

.next-btn.disabled {
    opacity: 0.5;
    cursor: not-allowed;
}

/* 进度指示器 */
.progress-dots {
    display: flex;
    justify-content: center;
    gap: 20rpx;
}

.progress-dot {
    width: 10rpx;
    height: 10rpx;
    border-radius: 50%;
    background: #ccc;
    transition: all 0.2s ease;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
}

.progress-dot.current {
    background: #666;
}

.progress-dot.answered {
    background: #ccc;
    width: 34rpx;
    height: 34rpx;
}

.answer-letter {
    font-size: 16rpx;
    font-weight: 600;
    color: #999;
    text-align: center;
    line-height: 1;
}
</style>
